<template>
  <div class="form-index">
    <!-- 背景层 -->
    <div class="background-layer" :style="getBackgroundStyle"></div>
    <!-- 内容层 -->
    <div class="content-layer">
      <el-row>
        <el-col :xs="24" :sm="20" :md="16" :lg="12" :xl="10">
          <div class="form-container">
            <!-- Logo -->
            <div v-if="formInfo.formAppearanceInfo?.showLogo" class="form-logo">
              <img :src="formInfo.formAppearanceInfo.logoImg" alt="logo" />
            </div>
            <!-- 表单头部 -->
            <div
              v-if="formInfo.formAppearanceInfo?.headerImg"
              class="form-header"
              :style="{
                backgroundImage: `url(${formInfo.formAppearanceInfo.headerImg})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center'
              }"
            ></div>
            <!-- 表单主体 -->
            <div class="form-body">
              <!-- 表单标题 -->
              <h2 class="form-title">{{ formInfo.label }}</h2>
              <!-- 表单描述 -->
              <div v-if="formInfo.description" class="form-description">
                {{ formInfo.description }}
              </div>
              <!-- 表单来源 -->
              <div v-if="formInfo.sourceId" class="form-source">
                来源：{{ formInfo.sourceName }}
              </div>

              <!-- 错误提示 -->
              <div v-if="error" class="error-message">
                <el-alert :title="error" type="error" :closable="false" show-icon />
              </div>

              <!-- 权限验证区域 -->
              <div v-if="permissions.length > 0" class="auth-section">
                <!-- 登录验证 -->
                <div v-if="hasPermission('useAuth') ">
                  <el-alert type="warning" :closable="false" show-icon>
                    <template #title>请登录后访问表单</template>
                  </el-alert>
                  <div class="auth-item">
                    <el-button type="primary" plain @click="handleLogin" style="width: 100%;">去登录</el-button>
                  </div>
                </div>
                <!-- 角色验证 -->
                <div v-else-if="hasPermission('useAccessAuth')">
                  <el-alert type="warning" :closable="false" show-icon>
                    <template #title>仅指定角色可访问表单，请联系管理员</template>
                  </el-alert>
                </div>
                <!-- 授权码验证 -->
                <div v-else-if="hasPermission('secretKey')">
                  <el-alert type="warning" :closable="false" show-icon>
                    <template #title>需要进行以下验证才能访问表单</template>
                  </el-alert>
                  <div class="auth-item">
                    <el-form
                      ref="authFormRef"
                      :model="authForm"
                      :rules="authRules"
                      label-position="top"
                      @submit.prevent
                    >
                      <el-form-item label="请输入授权码" prop="secretKey">
                        <el-input v-model="authForm.secretKey" placeholder="请输入授权码" clearable @keyup.enter="submitAuth" />
                      </el-form-item>
                      <el-form-item>
                        <el-button
                          type="primary"
                          :loading="verifying"
                          :disabled="verifying"
                          @click="submitAuth"
                        >
                          {{ verifying ? '验证中...' : '验证' }}
                        </el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { checkForm, getFormData } from '@/api/form'
import { parseQueryString } from '@/utils/tools'
// import { getToken } from '@ruifox-cms/utils'

const router = useRouter()
const route = useRoute()
const error = ref('')
const permissions = ref([])
const authFormRef = ref(null)
const verifying = ref(false)
const formInfo = ref({})
// const hasToken = ref(!!getToken())
// 授权表单数据
const authForm = ref({
  secretKey: ''
})

// 授权表单验证规则
const authRules = {
  secretKey: [{ required: true, message: '请输入授权码', trigger: 'blur' }]
}

// 计算背景样式
const getBackgroundStyle = computed(() => {
  const { backgroundType, backgroundColor, backgroundImg } = formInfo.value.formAppearanceInfo || {}
  if (backgroundType === 'img' && backgroundImg) {
    return {
      background: `url(${backgroundImg}) center/cover no-repeat fixed`,
      filter: 'blur(2px)'
    }
  }
  return {
    background: backgroundColor || '#f5f7fa'
  }
})

// 检查是否有某个权限
const hasPermission = (perm) => {
  return permissions.value.includes(perm)
}

// 跳转登录
const handleLogin = () => {
  if (process.env.NODE_ENV === 'development') {
    window.location.href = location.protocol + '//' + location.hostname + ':8100/login/index?redirect=' + location.href
  } else {
    window.location.href = location.origin + '/ram/login/index?redirect=' + location.href
  }
}

// 检查表单访问权限
const checkFormAccess = async () => {
  try {
    // 获取 formKey 并正确解码
    const formKey = route.query.formKey ? decodeURIComponent(route.query.formKey.replace(/ /g, '+')) : ''
    
    // 使用解码后的 formKey 调用接口
    const res = await checkForm({ formKey })

    // 保存表单基本信息
    formInfo.value = {
      formId: res.data.formId,
      label: res.data.label,
      description: res.data.description,
      sourceId: res.data.sourceId,
      sourceName: res.data.sourceName,
      formAppearanceInfo: res.data.formAppearanceInfo,
      formLink: location.href
    }

    localStorage.setItem('baseFormInfo', JSON.stringify(formInfo.value))

    if (!res.success) {
      error.value = res.message
      return
    } else {
      
      if (!res.data.permissionList || res.data.permissionList.length === 0) {
        let query = { formId: route.query.formId, sourceId: route.query.sourceId }
        const hashQuery = parseQueryString(window.location.search)
        hashQuery.callback ? query.callback = hashQuery.callback : ''
        router.push({
          path: '/form',
          query
        })
      } else {
        permissions.value = res.data.permissionList
      }
    }
  } catch (err) {
    error.value = '表单预检失败，请确保符合表单访问条件'
  }
}

// 提交授权验证
const submitAuth = async () => {
  if (!authFormRef.value || verifying.value) return

  try {
    await authFormRef.value.validate()
    verifying.value = true
    const data = {
      form: formInfo.value.formId,
      sourceId: formInfo.value.sourceId,
      key: authForm.value.secretKey
    }
    const res = await getFormData(data)

    if (res.success) {
      ElMessage.success('验证成功')
      let query = { formId: route.query.formId, sourceId: route.query.sourceId }
        const hashQuery = parseQueryString(window.location.hash)
        hashQuery.callback ? query.callback = hashQuery.callback : ''
      router.push({
        path: '/form',
        query
      })
    } else {
      // 验证失败时，允许重新验证
      verifying.value = false
      ElMessage.error(res.message || '验证失败')
    }
  } catch (err) {
    // 发生错误时，允许重新验证
    verifying.value = false
  }
}

onMounted(() => {
  checkFormAccess()
})
</script>

<style lang="scss" scoped>
.form-index {
  min-height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  position: relative;

  .background-layer {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: -1;
  }

  .content-layer {
    position: relative;
    z-index: 1;
    width: 100%;
    min-height: calc(100vh - 40px);
    display: flex;
    flex-direction: column;

    .el-row {
      margin: 0;
      flex: 1;
      display: flex;
      justify-content: center;

      .el-col {
        display: flex;
        flex-direction: column;
      }
    }
  }

  .form-container {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .form-logo {
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 10px;
      background: #fff;

      img {
        height: 100%;
        object-fit: contain;
      }
    }

    .form-header {
      height: 200px;
      background: #ccc;
      transition: background-image 0.3s;
    }

    .form-body {
      flex: 1;
      padding: 40px;
      display: flex;
      flex-direction: column;

      .form-title {
        margin: 0 0 20px;
        text-align: center;
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }

      .form-description {
        margin-bottom: 20px;
        text-align: center;
        font-size: 14px;
        color: #606266;
        line-height: 1.6;
      }

      .form-source {
        margin-bottom: 30px;
        text-align: center;
        font-size: 14px;
        color: #606266;
      }

      .error-message {
        margin-bottom: 20px;
      }

      .auth-section {
        max-width: 400px;
        margin: 0 auto;

        .auth-item {
          margin-top: 20px;
          padding: 20px;
          background: #f8f9fa;
          border-radius: 4px;

          .el-form-item:last-child {
            margin-bottom: 0;

            .el-button {
              width: 100%;
            }
          }
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .form-index {
    padding: 10px;

    .content-layer {
      min-height: calc(100vh - 20px);
    }
  }
}
</style>
